
import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { 
  Brain, 
  Plus, 
  Edit, 
  Trash2, 
  Star,
  ExternalLink,
  AlertCircle,
  CheckCircle
} from "lucide-react";
import ConfigTestPanel from "./ConfigTestPanel"; // 添加测试面板组件

const DEFAULT_LLM_PROVIDERS = [
  {
    name: "Base44 自带大模型",
    provider: "base44",
    model: "base44-pro",
    apiEndpoint: "built-in",
    supportedFeatures: ["text", "vision", "function_calling", "streaming"]
  },
  {
    name: "OpenAI GPT-4",
    provider: "openai",
    model: "gpt-4",
    apiEndpoint: "https://api.openai.com/v1/chat/completions",
    supportedFeatures: ["text", "vision", "function_calling"]
  },
  {
    name: "OpenAI GPT-3.5 Turbo",
    provider: "openai", 
    model: "gpt-3.5-turbo",
    apiEndpoint: "https://api.openai.com/v1/chat/completions",
    supportedFeatures: ["text", "function_calling"]
  },
  {
    name: "Claude-3 Sonnet",
    provider: "anthropic",
    model: "claude-3-sonnet-20240229",
    apiEndpoint: "https://api.anthropic.com/v1/messages",
    supportedFeatures: ["text", "vision"]
  },
  {
    name: "通义千问",
    provider: "dashscope",
    model: "qwen-turbo",
    apiEndpoint: "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
    supportedFeatures: ["text"]
  },
  {
    name: "文心一言",
    provider: "baidu",
    model: "ernie-bot-turbo",
    apiEndpoint: "https://aip.baiduce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant",
    supportedFeatures: ["text"]
  }
];

export default function LLMConfigManager({ configs, onSave, onDelete, onSetDefault, isLoading }) {
  const [showForm, setShowForm] = useState(false);
  const [editingConfig, setEditingConfig] = useState(null);
  const [formData, setFormData] = useState({
    configKey: "",
    provider: "",
    model: "",
    api_endpoint: "",
    api_key: "",
    max_tokens: 4000,
    temperature: 0.7,
    timeout: 30,
    supported_features: [],
    description: "",
    is_active: true,
    isDefault: false
  });
  const [showTestPanel, setShowTestPanel] = useState(false); // 添加测试面板显示状态

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    const configData = {
      configKey: formData.configKey,
      config_type: "llm_model",
      config_value: {
        provider: formData.provider,
        model: formData.model,
        api_endpoint: formData.api_endpoint,
        api_key: formData.api_key,
        max_tokens: parseInt(formData.max_tokens),
        temperature: parseFloat(formData.temperature),
        timeout: parseInt(formData.timeout),
        supported_features: formData.supported_features
      },
      description: formData.description,
      is_active: formData.is_active,
      isDefault: formData.isDefault
    };

    // 传递ID（如果正在编辑）
    await onSave(configData, editingConfig ? editingConfig.id : null);
    handleCancel();
  };

  const handleEdit = (config) => {
    setEditingConfig(config);
    setFormData({
      configKey: config.configKey,
      provider: config.config_value.provider || "",
      model: config.config_value.model || "",
      api_endpoint: config.config_value.api_endpoint || "",
      api_key: config.config_value.api_key || "",
      max_tokens: config.config_value.max_tokens || 4000,
      temperature: config.config_value.temperature || 0.7,
      timeout: config.config_value.timeout || 30,
      supported_features: config.config_value.supported_features || [],
      description: config.description || "",
      is_active: config.is_active !== undefined ? config.is_active : true,
      isDefault: config.isDefault !== undefined ? config.isDefault : false
    });
    setShowForm(true);
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingConfig(null);
    setFormData({
      configKey: "",
      provider: "",
      model: "",
      api_endpoint: "",
      api_key: "",
      max_tokens: 4000,
      temperature: 0.7,
      timeout: 30,
      supported_features: [],
      description: "",
      is_active: true,
      isDefault: false
    });
  };

  const handleUseTemplate = (template) => {
    const timestamp = Date.now();
    const isBase44 = template.provider === 'base44';
    setFormData({
      ...formData,
      configKey: `llm_${template.provider}_${timestamp}`,
      provider: template.provider,
      model: template.model,
      api_endpoint: isBase44 ? 'built-in' : template.apiEndpoint,
      api_key: isBase44 ? '' : formData.api_key, // Clear API key if Base44
      supported_features: template.supportedFeatures,
      description: `${template.name} 配置`
    });
  };

  const toggleFeature = (feature) => {
    setFormData(prev => ({
      ...prev,
      supported_features: prev.supported_features.includes(feature)
        ? prev.supported_features.filter(f => f !== feature)
        : [...prev.supported_features, feature]
    }));
  };

  const isBase44Provider = formData.provider === 'base44';

  return (
    <div className="space-y-6">
      {/* Add New Config Button */}
      <div className="flex justify-between items-center">
        <h3 className="text-xl font-semibold">大模型配置管理</h3>
        <div className="flex gap-3">
          <Button 
            onClick={() => setShowTestPanel(!showTestPanel)}
            variant="outline"
            className="border-purple-200 text-purple-700 hover:bg-purple-50"
          >
            {showTestPanel ? '隐藏' : '显示'}配置测试
          </Button>
          <Button 
            onClick={() => setShowForm(true)}
            className="bg-blue-600 hover:bg-blue-700"
          >
            <Plus className="w-4 h-4 mr-2" />
            添加大模型配置
          </Button>
        </div>
      </div>

      {/* Config Test Panel - 添加测试面板 */}
      {showTestPanel && (
        <div className="mb-6">
          <ConfigTestPanel
            llmConfigs={configs.filter(c => c.is_active)}
          />
        </div>
      )}

      {/* Config Form */}
      {showForm && (
        <Card className="shadow-lg border-0">
          <CardHeader className="bg-gradient-to-r from-blue-50 to-indigo-50 border-b">
            <CardTitle className="flex items-center gap-2">
              <Brain className="w-5 h-5 text-blue-600" />
              {editingConfig ? '编辑大模型配置' : '添加大模型配置'}
            </CardTitle>
          </CardHeader>
          <CardContent className="p-6">
            {!editingConfig && (
              <div className="mb-6">
                <Label className="text-sm font-medium text-gray-700 mb-3 block">
                  选择预设模板（可选）
                </Label>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {DEFAULT_LLM_PROVIDERS.map((template, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      onClick={() => handleUseTemplate(template)}
                      className="justify-start h-auto p-3 text-left"
                    >
                      <div>
                        <div className="font-medium">{template.name}</div>
                        <div className="text-xs text-gray-500 mt-1">
                          {template.provider} • {template.supportedFeatures.join(', ')}
                        </div>
                      </div>
                    </Button>
                  ))}
                </div>
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="configKey">配置名称 *</Label>
                  <Input
                    id="configKey"
                    value={formData.configKey}
                    onChange={(e) => setFormData({...formData, configKey: e.target.value})}
                    placeholder="例如: llm_openai_gpt4"
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="provider">提供商 *</Label>
                  <Input
                    id="provider"
                    value={formData.provider}
                    onChange={(e) => setFormData({...formData, provider: e.target.value})}
                    placeholder="例如: openai, anthropic"
                    required
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="model">模型名称 *</Label>
                  <Input
                    id="model"
                    value={formData.model}
                    onChange={(e) => setFormData({...formData, model: e.target.value})}
                    placeholder="例如: gpt-4, base44-pro"
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="api_endpoint">API端点 *</Label>
                  <Input
                    id="api_endpoint"
                    value={formData.api_endpoint}
                    onChange={(e) => setFormData({...formData, api_endpoint: e.target.value})}
                    placeholder={isBase44Provider ? "内置调用，无需填写" : "https://api.openai.com/v1/chat/completions"}
                    required={!isBase44Provider}
                    disabled={isBase44Provider}
                    className={isBase44Provider ? "bg-gray-100" : ""}
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="api_key">API密钥 *</Label>
                <Input
                  id="api_key"
                  type="password"
                  value={formData.api_key}
                  onChange={(e) => setFormData({...formData, api_key: e.target.value})}
                  placeholder={isBase44Provider ? "内置调用，无需API密钥" : "请输入API密钥"}
                  required={!isBase44Provider}
                  disabled={isBase44Provider}
                  className={isBase44Provider ? "bg-gray-100" : ""}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="max_tokens">最大Token数</Label>
                  <Input
                    id="max_tokens"
                    type="number"
                    value={formData.max_tokens}
                    onChange={(e) => setFormData({...formData, max_tokens: e.target.value})}
                    min="1"
                    max="32000"
                  />
                </div>
                <div>
                  <Label htmlFor="temperature">温度值</Label>
                  <Input
                    id="temperature"
                    type="number"
                    step="0.1"
                    value={formData.temperature}
                    onChange={(e) => setFormData({...formData, temperature: e.target.value})}
                    min="0"
                    max="2"
                  />
                </div>
                <div>
                  <Label htmlFor="timeout">超时时间(秒)</Label>
                  <Input
                    id="timeout"
                    type="number"
                    value={formData.timeout}
                    onChange={(e) => setFormData({...formData, timeout: e.target.value})}
                    min="5"
                    max="300"
                  />
                </div>
              </div>

              <div>
                <Label className="text-sm font-medium text-gray-700 mb-3 block">
                  支持的功能
                </Label>
                <div className="flex flex-wrap gap-2">
                  {['text', 'vision', 'function_calling', 'streaming', 'embeddings'].map(feature => (
                    <Button
                      key={feature}
                      type="button"
                      variant={formData.supported_features.includes(feature) ? "default" : "outline"}
                      size="sm"
                      onClick={() => toggleFeature(feature)}
                    >
                      {feature}
                    </Button>
                  ))}
                </div>
              </div>

              <div>
                <Label htmlFor="description">描述</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData({...formData, description: e.target.value})}
                  placeholder="配置描述..."
                  rows={3}
                />
              </div>

              <div className="flex items-center gap-6">
                <div className="flex items-center space-x-2">
                  <Switch
                    id="is_active"
                    checked={formData.is_active}
                    onCheckedChange={(checked) => setFormData({...formData, is_active: checked})}
                  />
                  <Label htmlFor="is_active">启用此配置</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch
                    id="isDefault"
                    checked={formData.isDefault}
                    onCheckedChange={(checked) => setFormData({...formData, isDefault: checked})}
                  />
                  <Label htmlFor="isDefault">设为默认</Label>
                </div>
              </div>

              <div className="flex justify-end gap-3 pt-4 border-t">
                <Button type="button" variant="outline" onClick={handleCancel}>
                  取消
                </Button>
                <Button type="submit" className="bg-blue-600 hover:bg-blue-700">
                  {editingConfig ? '更新配置' : '创建配置'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      )}

      {/* Configs List */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {isLoading ? (
          Array(4).fill(0).map((_, i) => (
            <Card key={i} className="animate-pulse">
              <CardHeader>
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                <div className="h-3 bg-gray-200 rounded w-1/2"></div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="h-3 bg-gray-200 rounded"></div>
                  <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                </div>
              </CardContent>
            </Card>
          ))
        ) : configs.length === 0 ? (
          <div className="col-span-full">
            <Card className="text-center py-12">
              <CardContent>
                <Brain className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  暂无大模型配置
                </h3>
                <p className="text-gray-500 mb-6">
                  添加您的第一个大模型配置以开始使用AI功能
                </p>
                <Button
                  onClick={() => setShowForm(true)}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加配置
                </Button>
              </CardContent>
            </Card>
          </div>
        ) : (
          configs.map((config) => (
            <Card key={config.id} className="shadow-lg border-0">
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
                      <Brain className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <CardTitle className="text-lg font-bold text-gray-900">
                        {config.configKey}
                      </CardTitle>
                      <div className="flex items-center gap-2 mt-1">
                        <Badge variant={config.is_active ? "default" : "secondary"}>
                          {config.is_active ? "活跃" : "未活跃"}
                        </Badge>
                        {config.isDefault && (
                          <Badge className="bg-yellow-100 text-yellow-700 border-yellow-200">
                            <Star className="w-3 h-3 mr-1" />
                            默认
                          </Badge>
                        )}
                      </div>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-1">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleEdit(config)}
                      className="w-8 h-8"
                    >
                      <Edit className="w-4 h-4" />
                    </Button>
                    {!config.isDefault && (
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => onSetDefault(config.id, config.configKey)}
                        className="w-8 h-8"
                        title="设为默认"
                      >
                        <Star className="w-4 h-4" />
                      </Button>
                    )}
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => onDelete(config.id)}
                      className="w-8 h-8 text-red-600 hover:text-red-700"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              
              <CardContent className="pt-0">
                <div className="space-y-3">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-gray-500">提供商:</span>
                      <span className="ml-2 font-medium">{config.config_value.provider}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">模型:</span>
                      <span className="ml-2 font-medium">{config.config_value.model}</span>
                    </div>
                  </div>
                  
                  {config.description && (
                    <p className="text-sm text-gray-600 line-clamp-2">
                      {config.description}
                    </p>
                  )}
                  
                  {config.config_value.supported_features && (
                    <div className="flex flex-wrap gap-1">
                      {config.config_value.supported_features.map((feature, index) => (
                        <Badge key={index} variant="outline" className="text-xs">
                          {feature}
                        </Badge>
                      ))}
                    </div>
                  )}
                  
                  <div className="flex items-center gap-4 text-xs text-gray-500 pt-2 border-t">
                    <span>Max Tokens: {config.config_value.max_tokens}</span>
                    <span>Temperature: {config.config_value.temperature}</span>
                    <span>Timeout: {config.config_value.timeout}s</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  );
}
